const request = require('request');
const config  = require('../config/config');

class js_login{
    constructor(username,password) {
        this.username = username;
        this.password = password;
    }

    async do(){
        return new Promise((resolve, reject) => {
            let options = {
                url:'https://ext.junglescout.com/api/v1/users/initial_authentication',
                method:'POST',
                json:true,
                proxy:`http://${config.PROXY.HOST}:${config.PROXY.PORT}`,
                headers: {
                    "content-type": "application/json",
                    "accept": "application/json, text/javascript, */*; q=0.01",
                    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
                    "origin": "chrome-extension://bckjlihkmgolmgkchbpiponapgjenaoa",
                    "cookie":"AWSALB=vgMDox4tZPac9FpmB8/vqn2jqen1oXCnx1NQFkDARcIJCkvcx4xvx6BUW/MZyRqkz5T1fzzA+04Z4nZPy+getie+tLhu+/AzO+cKVWPqLH58fKYokqDE+aNP+wMu;AWSALBCORS=vgMDox4tZPac9FpmB8/vqn2jqen1oXCnx1NQFkDARcIJCkvcx4xvx6BUW/MZyRqkz5T1fzzA+04Z4nZPy+getie+tLhu+/AzO+cKVWPqLH58fKYokqDE+aNP+wMu;"
                },
                body: { username: this.username, password: this.password, app: 'jsp' }
            }

            request(options,async (err,response,body) => {
                if(err){
                    console.log(`js plugin登录失败 错误简文:${JSON.stringify(err)}`);
                    reject(err.message)
                }else{
                    if(!body){
                        console.log(`js plugin登录失败 响应为空`);
                        reject(null);

                    }else{
                        let status = body.status;
                        if(status){
                            console.log(`js plugin登录成功 `);
                            resolve(body);
                        }else{
                            console.log(`js plugin登录失败 错误简文：${JSON.stringify(body)}`);
                            reject(body.message);
                        }
                    }
                }
            })
        })
    }

}
module.exports = js_login;
